﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml;
using System.Xml.Linq;
using System.IO; 
namespace ChatServer.model
{

    public class UserSocket
    {
        //private variables
        private Socket _userSocket;

        public Socket UserUserSocket
        {
            get { return _userSocket; }
        }

        //constructor will run method to connect socket
        public UserSocket(IPAddress client, int port)
        {
            //run method for connecting to socket
            _userSocket = ConnectSocket(client, port);

        }
        
        //message sent across usersocket
        public void sendMessage(XmlDocument doc)
        {  
            //create instance of class
            Chat creator = new Chat();
            //convert to byte array
            byte[] bytes = creator.chatToByteArray(doc);

            //send xml message to active user
            _userSocket.Send(bytes);
            
         }

        //method will connect socket to client
        private static Socket ConnectSocket(IPAddress server, int port)
        {
            Socket s = null;
            IPHostEntry hostEntry = null;

            // Get host related information.
            hostEntry = Dns.GetHostEntry(server);

            // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
            // an exception that occurs when the host IP Address is not compatible with the address family
            // (typical in the IPv6 case).
            foreach (IPAddress address in hostEntry.AddressList)
            {
                IPEndPoint ipe = new IPEndPoint(address, port);
                
                Socket tempSocket =
                    new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

                tempSocket.Connect(ipe);

                if (tempSocket.Connected)
                {
                    s = tempSocket;
                    break;
                }
                else
                {
                    continue;
                }
            }
            return s;
        }
             

        //internal user property with a getter and setter. 
        //property to expose IP address / required parameter of constructer/just a getter
        // be able to receive a user object. just get it and hang on to it
        //be able to receive a chat object. make it an argument of send message
        //send the xml in chat object.
    }
}

